//
//  FreshFoodDetailView.swift
//  SmartHousekeeper
//
//  Created by 刘森 on 2020/2/22.
//  Copyright © 2020 LS. All rights reserved.
//

import UIKit

//MARK: - 商品详情容器
class FreshFoodDetailView: UIScrollView {
    
    
    
    var foodHeaderImageView: UIImageView?
    var freshFoodDetailCell: FreshFoodDetailCell?
    var freshFoodDetailSetMealCell: FreshFoodDetailSetMealCell?
    var freshFoodDetailTitleCell: FreshFoodDetailTitleCell?
    var freshFoodDetailImageTitleCell: FreshFoodDetailImageTitleCell?
    var freshFoodDetailEvaluateCell: FreshFoodDetailEvaluateCell?
    var getTopHeight: CGFloat = 0.0
    
    let lightGrayLine = { () -> UIView in
        return UIView(backgroundColor: .lightGray)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = KColorRGBA(248, 245, 242)

    }
    
    override func layoutSubviews() {
        
        var lastView: UIView?
        
        if (foodHeaderImageView != nil) {
            self.foodHeaderImageView?.snp.makeConstraints({ (make) in
                make.left.top.width.right.equalToSuperview()
                make.height.equalTo(self.foodHeaderImageView!.snp.width).multipliedBy(0.538)
            })
            lastView = foodHeaderImageView
        }
        if (freshFoodDetailCell != nil) {
            self.freshFoodDetailCell?.snp.makeConstraints({ (make) in
                make.left.width.right.equalToSuperview()
                make.top.equalTo(lastView?.snp.bottom ?? self.snp.top)
                make.height.equalTo(Adapter(160))
            })
            lastView = freshFoodDetailCell
        }
        if (freshFoodDetailSetMealCell != nil) {
            self.freshFoodDetailSetMealCell?.snp.makeConstraints({ (make) in
                make.left.width.right.equalToSuperview()
                make.top.equalTo(lastView?.snp.bottom ?? self.snp.top)
                make.height.equalTo(Adapter(160))
            })
            lastView = freshFoodDetailSetMealCell
        }
        
        if (freshFoodDetailTitleCell != nil) {
            self.freshFoodDetailTitleCell?.snp.makeConstraints({ (make) in
                make.left.width.right.equalToSuperview()
                make.top.equalTo(lastView?.snp.bottom ?? self.snp.top)
                make.height.equalTo(Adapter(140))
            })
            lastView = freshFoodDetailTitleCell
        }
        
        if (freshFoodDetailImageTitleCell != nil) {
            self.freshFoodDetailImageTitleCell?.snp.makeConstraints({ (make) in
                make.left.width.right.equalToSuperview()
                make.top.equalTo(lastView?.snp.bottom ?? self.snp.top)
                make.height.equalTo(Adapter(64))
            })
            lastView = freshFoodDetailImageTitleCell
        }
        
        if (freshFoodDetailEvaluateCell != nil) {
            self.freshFoodDetailEvaluateCell?.snp.makeConstraints({ (make) in
                make.left.width.right.equalToSuperview()
                make.top.equalTo(lastView?.snp.bottom ?? self.snp.top)
                make.height.equalTo(Adapter(100))
            })
            lastView = freshFoodDetailEvaluateCell
        }
        
        if (lastView != nil) {
            self.layoutIfNeeded()
            self.setNeedsLayout()
            self.contentSize = CGSize(width: 0, height: lastView!.frame.maxY)
        }
        
    }
    
    var model: FreshFoodSecondLevelCellModel? {
        didSet {
            
            if let imageName = self.model?.imageName {
                if foodHeaderImageView == nil {
                    foodHeaderImageView = UIImageView()
                    self.addSubview(foodHeaderImageView!)
                }
                foodHeaderImageView?.image = ImageName(imageName)
            }
            
            if let model = self.model {
                if freshFoodDetailCell == nil {
                    freshFoodDetailCell = FreshFoodDetailCell()
                    self.addSubview(freshFoodDetailCell!)
                }
                freshFoodDetailCell?.model = model
            }
            
            if let model = self.model {
                if freshFoodDetailSetMealCell == nil {
                    freshFoodDetailSetMealCell = FreshFoodDetailSetMealCell()
                    self.addSubview(freshFoodDetailSetMealCell!)
                }
                freshFoodDetailSetMealCell?.models = [model,model]
            }
            
            if (freshFoodDetailTitleCell == nil) {
                freshFoodDetailTitleCell = FreshFoodDetailTitleCell()
                self.addSubview(freshFoodDetailTitleCell!)
            }
            
            if (freshFoodDetailImageTitleCell == nil) {
                freshFoodDetailImageTitleCell = FreshFoodDetailImageTitleCell()
                self.addSubview(freshFoodDetailImageTitleCell!)
            }
            
            if (freshFoodDetailEvaluateCell == nil) {
                freshFoodDetailEvaluateCell = FreshFoodDetailEvaluateCell()
                self.addSubview(freshFoodDetailEvaluateCell!)
            }
            
        }
    }
    
    override func draw(_ rect: CGRect) {
        let arr = [foodHeaderImageView, freshFoodDetailCell, freshFoodDetailSetMealCell, freshFoodDetailTitleCell, freshFoodDetailImageTitleCell].compactMap{$0}
        arr.forEach{
            let layer = CALayer()
            let frame = $0.bounds
            layer.frame = CGRect(x: 0, y: frame.maxY - 1, width: frame.width, height: 1)
            layer.backgroundColor = UIColor.lightGray.cgColor
            $0.layer.addSublayer(layer)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: - 单个商品详情单元格
class FreshFoodDetailCell: UIView {
    
    var model: FreshFoodSecondLevelCellModel? {
        didSet {
            self.foodNameLabel.text = self.model?.foodName
            self.foodAreaLabel.text = self.model?.foodArea
            self.foodPlusLabel.text = " 冷冻 "
            if let price = self.model?.foodPrice, let foodUnit = self.model?.foodUnit {
                self.foodPriceAndUnitLabel.attributedText = getPriceAttstr(value: price, unit: foodUnit)
            }
        }
    }
    
    lazy private var foodNameLabel: UILabel = {
        let value = UILabel(textColor: UIColor.black, textFont: KFont(Adapter(20)))
        return value
    }()
    lazy private var foodPlusLabel: UILabel = {
        let value = UILabel(textColor: UIColor.white, textFont: KFont(Adapter(15)))
        value.backgroundColor = KColorRGBA(185, 159, 128)
        return value
    }()
    lazy private var foodAreaLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(129, 129, 129), textFont: KFont(Adapter(15)))
        return value
    }()
    lazy private var foodPriceAndUnitLabel: UILabel = {
        let value = UILabel()
        return value
    }()
    lazy var addAndSubView = FreshFoodSecondLevelAddAndSubView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = KColorRGBA(248, 245, 242)
        self.addSubviews([foodNameLabel,foodPlusLabel, foodAreaLabel, foodPriceAndUnitLabel, addAndSubView])
    }
    
    override func layoutSubviews() {
        foodNameLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(Adapter(30))
        }
        foodPlusLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(foodNameLabel)
            make.left.equalTo(foodNameLabel.snp.right).offset(Adapter(4))
        }
        foodAreaLabel.snp.makeConstraints { (make) in
            make.left.equalTo(foodNameLabel)
            make.top.equalTo(foodNameLabel.snp.bottom).offset(Adapter(8))
        }
        addAndSubView.snp.makeConstraints { (make) in
            make.height.equalTo(Adapter(30))
            make.bottom.equalTo(foodPriceAndUnitLabel)
            make.right.equalToSuperview().offset(-Adapter(30))
        }
        foodPriceAndUnitLabel.snp.makeConstraints { (make) in
            make.top.equalTo(foodAreaLabel.snp.bottom).offset(Adapter(30))
            make.left.equalTo(foodAreaLabel)
            make.right.lessThanOrEqualTo(addAndSubView.snp.left).offset(-Adapter(30))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getPriceAttstr(value: String, unit: String) -> NSAttributedString {
        let fillUnit = "  /  \(unit)"
        let string = String(format: "￥%@%@", value, fillUnit)
        let attrStr = NSMutableAttributedString(string: string)
        let subTextRange = NSMakeRange(0, string.count)
        attrStr.addAttributes([NSAttributedString.Key.font: KFontBold(Adapter(16)), NSAttributedString.Key.foregroundColor:  KColorRGBA(58, 130, 232)], range: subTextRange)
        let range: Range = string.range(of: value)!
        let location: Int = string.distance(from: value.startIndex, to: range.lowerBound)
        let value1: NSValue = NSValue(range: NSMakeRange(location, value.count))
        attrStr.addAttributes([NSAttributedString.Key.foregroundColor: KColorRGBA(58, 130, 232), NSAttributedString.Key.font: KFontBold(Adapter(24))], range: value1.rangeValue)
        
        let range2: Range = string.range(of: fillUnit)!
        let location2: Int = string.distance(from: fillUnit.startIndex, to: range2.lowerBound)
        let value2: NSValue = NSValue(range: NSMakeRange(location2, fillUnit.count))
        attrStr.addAttributes([NSAttributedString.Key.foregroundColor: KColorRGBA(129, 129, 129), NSAttributedString.Key.font: KFont(Adapter(15))], range: value2.rangeValue)
        
        return attrStr
    }
    
}

//MARK: - 套餐商品单元格
class FreshFoodDetailSetMealCell: UIView {
    var models: [FreshFoodSecondLevelCellModel]? {
        didSet {
            if let tempModels = self.models {
                self.foodViews = [TopImageBottomLabelView]()
                self.addViews = [UIImageView]()
                
                for (idx, data) in tempModels.enumerated() {
                    let label = TopImageBottomLabelView()
                    label.setData(image: data.imageName, title: data.foodName)
                    label.tag = foodViewTag + idx
                    self.addSubview(label)
                    foodViews?.append(label)
                    if idx == tempModels.count - 1 {
                        break
                    }
                    let imageView = UIImageView(image: ImageName("add-fill"))
                    self.addSubview(imageView)
                    addViews?.append(imageView)
                }
                
                let price = tempModels.compactMap{$0.foodPrice.floatValue()}.reduce(0, +)
                actualPaymentLabel.attributedText = getPaymentTitle(price)
            }
        }
    }
    lazy private var titleLabel: UILabel = {
        let value = UILabel(textColor:  KColorRGBA(129, 129, 129), textFont: KFont(Adapter(16)))
        value.text = "套餐优惠"
        return value
    }()
    lazy var actualPaymentLabel: UILabel = {
        let value = UILabel()
        value.numberOfLines = 2
        return value
    }()
    lazy var addAndSubView = FreshFoodSecondLevelAddAndSubView()
    let foodViewTag = 30000
    var foodViews: [TopImageBottomLabelView]?
    var addViews: [UIImageView]?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubviews([titleLabel, actualPaymentLabel, addAndSubView, actualPaymentLabel])
    }
    
    override func layoutSubviews() {
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(Adapter(30))
            make.top.equalToSuperview().offset(Adapter(15))
        }
        
        var lastView: UIView?
        var lastFoodView: UIView?
        if let foods = self.foodViews, let adds = self.addViews {
            for (idx, food) in foods.enumerated() {
                food.snp.makeConstraints { (make) in
                    make.left.equalTo(lastView?.snp.right ?? self).offset(lastView != nil ? Adapter(10) : Adapter(30))
                    make.width.equalTo(Adapter(66))
                    make.top.equalTo(titleLabel.snp.bottom).offset(Adapter(10))
                }
                if let addView = adds[idx, true], idx != foods.count - 1 {
                    addView.snp.makeConstraints { (make) in
                        make.centerY.equalTo(food)
                        make.left.equalTo(food.snp.right).offset(Adapter(10))
                        make.width.height.equalTo(Adapter(30))
                    }
                    lastView = addView
                }
                lastFoodView = food
            }
        }
        
        addAndSubView.snp.makeConstraints { (make) in
            make.height.equalTo(Adapter(22))
            make.bottom.equalTo(lastFoodView ?? self)
            make.right.equalToSuperview().offset(-Adapter(30))
        }
        
        actualPaymentLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(Adapter(6))
            make.right.equalToSuperview().offset(-Adapter(30))
            
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getPaymentTitle(_ value: Float) -> NSMutableAttributedString {
        let currency = "￥"
        let price = String(format: "%.2f", value)
        let subText = "实付\n" + currency + price
        let attrStr = NSMutableAttributedString(string: subText)
        let style = NSMutableParagraphStyle()
        style.alignment = .right
        style.lineSpacing = Adapter(10)
        let subTextRange = NSMakeRange(0, subText.count)
        attrStr.addAttributes([NSAttributedString.Key.paragraphStyle: style], range: subTextRange)
        attrStr.addAttributes([NSAttributedString.Key.font: KFontBold(Adapter(15))], range: subTextRange)
        attrStr.addAttributes([NSAttributedString.Key.foregroundColor:  KColorRGBA(129, 129, 129)], range: subTextRange)
        
        let range: Range = subText.range(of: currency)!
        let location: Int = subText.distance(from: price.startIndex, to: range.lowerBound)
        let value: NSValue = NSValue(range: NSMakeRange(location, currency.count))
        attrStr.addAttributes([NSAttributedString.Key.font: KFontBold(Adapter(12)), NSAttributedString.Key.foregroundColor: KColorRGBA(255, 70, 8)], range: value.rangeValue)
        
        let range1: Range = subText.range(of: price)!
        let location1: Int = subText.distance(from: price.startIndex, to: range1.lowerBound)
        let value1: NSValue = NSValue(range: NSMakeRange(location1, price.count))
        attrStr.addAttributes([NSAttributedString.Key.font: KFontBold(Adapter(20)), NSAttributedString.Key.foregroundColor: KColorRGBA(255, 70, 8)], range: value1.rangeValue)
        return attrStr
        
    }
}

class TopImageBottomLabelView: UIView {
    
    func setData(image: String, title: String) {
        imageView.image = ImageName(image)
        label.text = title
    }
    
    lazy var label: UILabel = {
        let value = UILabel(textColor: KColorRGBA(129, 129, 129), textFont: KFont(Adapter(15)))
        value.adjustsFontSizeToFitWidth = true
        value.textAlignment = .center
        return value
    }()
    lazy var imageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubviews([label, imageView])
    }
    
    override func layoutSubviews() {
        
        imageView.snp.makeConstraints { (make) in
            make.left.top.right.width.equalToSuperview()
            make.height.equalTo(imageView.snp.width)
        }
        
        label.snp.makeConstraints { (make) in
            make.left.width.right.bottom.equalToSuperview()
            make.top.equalTo(imageView.snp.bottom).offset(6)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: - 商品详情单元格
class FreshFoodDetailTitleCell: UIView {
    
    func getData()  {
        detailLabel.text
            = """
               产自三门镇的湾塘乡
               
               包装费：每份额外收取 0.8 元
              """

    }
    
    lazy var titleLabel: UILabel = {
        let value = UILabel(textColor: UIColor.black , textFont: KFontBold(Adapter(22)))
        value.text = "商品详情"
        return value
    }()
    lazy var detailLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(129, 129, 129), textFont: KFont(Adapter(15)))
        value.numberOfLines = 0
        return value
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubviews([titleLabel,detailLabel])
        self.backgroundColor = KColorRGBA(248, 245, 242)
        getData()
    }
    
    override func layoutSubviews() {
        titleLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(Adapter(26))
        }
        detailLabel.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(Adapter(10))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - 商品详情单元格
class FreshFoodDetailImageTitleCell: UIView {
    
    lazy var titleButton: UIButton = {
        let value = UIButton()
        value.setImage(ImageName("shopBag"), for: .normal)
        value.setTitle(" 本地直达到家，额外收取6元", for: .normal)
        value.setTitleColor(KColorRGBA(129, 129, 129), for: .normal)
        value.titleLabel?.font = KFont(Adapter(15))
        return value
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(titleButton)
        self.backgroundColor = KColorRGBA(248, 245, 242)
    }
    
    override func layoutSubviews() {
        titleButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(Adapter(30))
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - 商品评价单元格
class FreshFoodDetailEvaluateCell: UIView {
    
    
    lazy var titleLabel: UILabel = {
        let value = UILabel()
        value.attributedText = getEvaluatAttstr(evaluat: "100%")
        return value
    }()
    lazy var detailLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(129, 129, 129), textFont: KFont(Adapter(15)))
        value.text = "暂无评价"
        return value
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubviews([titleLabel,detailLabel])
        self.backgroundColor = KColorRGBA(248, 245, 242)
    }
    
    override func layoutSubviews() {
        titleLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(Adapter(26))
        }
        detailLabel.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(Adapter(10))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getEvaluatAttstr(evaluat: String) -> NSAttributedString {
        let fillEvaluat = "（\(evaluat) 好评）"
        let string = String(format: "评价%@", fillEvaluat)
        let attrStr = NSMutableAttributedString(string: string)
        let subTextRange = NSMakeRange(0, string.count)
        attrStr.addAttributes([NSAttributedString.Key.font: KFontBold(Adapter(22)), NSAttributedString.Key.foregroundColor:  UIColor.black], range: subTextRange)
        let range: Range = string.range(of: fillEvaluat)!
        let location: Int = string.distance(from: fillEvaluat.startIndex, to: range.lowerBound)
        let value1: NSValue = NSValue(range: NSMakeRange(location, fillEvaluat.count))
        attrStr.addAttributes([NSAttributedString.Key.foregroundColor: KColorRGBA(129, 129, 129), NSAttributedString.Key.font: KFontBold(Adapter(14))], range: value1.rangeValue)
        
        
        return attrStr
    }
}





